<template>
	<div class="system-add-user-container">
		<el-dialog v-model="dialog" :title="!isAdd ? '修改微信应用' : '新增微信应用'" width="60%" :before-close="handleClose">
			<el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
				<el-form-item label="应用名称" prop="appName">
					<el-input v-model="form.appName" maxlength="20" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="appId" prop="appId">
					<el-input v-model="form.appId"></el-input>
				</el-form-item>
				<el-form-item label="appSecret" prop="appSecret">
					<el-input v-model="form.appSecret" type="appSecret"></el-input>
				</el-form-item>
				<el-form-item label="alipayRootCert.crt" prop="rootCertPath">
					<CertUpload @handleSuccess="rootCertPathHandle" />
					<div><el-input v-model="form.rootCertPath"></el-input></div>
				</el-form-item>
				<el-form-item label="alipayCertPublicKey_RSA2.crt" prop="alipayPublicCertPath">
					<CertUpload @handleSuccess="alipayPublicCertPathHandle" />
					<div><el-input v-model="form.alipayPublicCertPath"></el-input></div>
				</el-form-item>
				<el-form-item label="appCertPublicKey.crt" prop="certPath">
					<CertUpload @handleSuccess="certPathHandle" />
					<div><el-input v-model="form.certPath"></el-input></div>
				</el-form-item>
				<el-form-item label="小程序码" prop="miniCodeUrl">
					<el-upload
						class="avatar-uploader"
						:action="action"
						:headers="headers"
						:show-file-list="false"
						:before-upload="beforeUpload"
						:on-success="handleSuccess"
						:on-error="handleError"
					>
						<img v-if="form.miniCodeUrl" :src="form.miniCodeUrl" class="avatar" />
						<el-icon class="avatar-uploader-icon" v-else> <ele-Plus /> </el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :loading="loading" @click="submitForm(formRef)">确 认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, defineAsyncComponent } from 'vue';
import { addObj, editObj, getById } from '/@/api/miniapp/alipay/alipayapp';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import type { UploadProps } from 'element-plus';
import { Session } from '/@/utils/storage';
export default defineComponent({
	components: { CertUpload: defineAsyncComponent(() => import('/@/components/certUpload/index.vue')) },
	emits: ['initPage'],
	setup(props, { emit }) {
		const data = reactive({
			form: {
				appId: undefined,
				appSecret: '',
				rootCertPath: '',
				aesKey: '',
				appName: '',
				miniCodeUrl: '',
				alipayPublicCertPath: '',
				certPath: '',
			},
			rules: {
				appId: [
					{
						required: true,
						message: '请输入APPID',
						trigger: 'change',
					},
				],
				appSecret: [
					{
						required: true,
						message: '请输入AppSecret',
						trigger: 'change',
					},
				],
				appName: [
					{
						required: true,
						message: '请输入应用名称',
						trigger: 'change',
					},
				],
			},
		});
		const dialog = ref(false);
		const loading = ref(false);
		const formRef = ref();
		const isAdd = ref(true);
		const headers = {
			satoken: Session.get('token'),
		};
		const action = '/upms/file/upload?fileType=image';
		const defaultProps = {
			children: 'children',
			label: 'name',
		};
		const initForm = (row: any | undefined) => {
			dialog.value = true;
			if (row && row.appId) {
				isAdd.value = false;
				getDetail(row.appId);
			}
		};
		const getDetail = (id: string) => {
			loading.value = true;
			getById(id).then((response) => {
				data.form = response.data.data;
				loading.value = false;
			});
		};
		/**
		 * 关闭事件
		 */
		const handleClose = () => {
			resetForm(formRef.value);
		};
		/**
		 * 重置表单
		 */
		const resetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			data.form.appId = undefined;
			loading.value = false;
			dialog.value = false;
			isAdd.value = true;
			formEl.resetFields();
		};
		/**
		 * 提交按钮
		 */
		const submitForm = async (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					loading.value = true;
					if (!isAdd.value) {
						//修改
						edit();
					} else {
						//新增
						add();
					}
				}
			});
		};
		/**
		 * 新增
		 */
		const add = () => {
			addObj(data.form)
				.then((response) => {
					resetForm(formRef.value);
					ElMessage.success('新增成功');

					emit('initPage');
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 修改
		 */
		const edit = () => {
			editObj(data.form)
				.then((response) => {
					resetForm(formRef.value);
					ElMessage.success('修改成功');
					emit('initPage');
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 上传前
		 */
		const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
			if (rawFile.type !== 'image/jpeg') {
				ElMessage.error('Avatar picture must be JPG format!');
				return false;
			} else if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage.error('Avatar picture size can not exceed 2MB!');
				return false;
			}
			return true;
		};
		/**
		 * 上传成功事件
		 */
		const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
			data.form.miniCodeUrl = response.data;
		};
		/**
		 * 上传失败事件
		 */
		const handleError: UploadProps['onError'] = (error) => {
			ElMessage.error(error + '');
		};
		const rootCertPathHandle = (url: string) => {
			data.form.rootCertPath = url;
		};
		const alipayPublicCertPathHandle = (url: string) => {
			data.form.alipayPublicCertPath = url;
		};
		const certPathHandle = (url: string) => {
			data.form.certPath = url;
		};
		return {
			isAdd,
			action,
			dialog,
			headers,
			loading,
			formRef,
			defaultProps,
			initForm,
			handleClose,
			submitForm,
			beforeUpload,
			handleSuccess,
			handleError,
			certPathHandle,
			rootCertPathHandle,
			alipayPublicCertPathHandle,
			...toRefs(data),
		};
	},
});
</script>

<style scoped>
.avatar-uploader .avatar {
	width: 140px;
	height: 140px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 26px;
	color: #8c939d;
	width: 140px;
	height: 140px;
	text-align: center;
}
</style>
